// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html


const version = "103";
const dataKey = "StorageData";
interface IDataUnit {
    key: string,
    val: any
}
export default class Stor {
    private static dataMap: Map<string, any> = new Map();
    public static save() {
        localStorage.setItem("version", version);
        let data: IDataUnit[] = [];
        this.dataMap.forEach((v, k) => {
            data.push({ key: k, val: v });
        });
        localStorage.setItem(dataKey, JSON.stringify(data));
        console.warn("保存存档=====");
    }
    public static async load() {
        let d = localStorage.getItem(dataKey);
        let data = d ? JSON.parse(d) as IDataUnit[] : null;
        this.dataMap = new Map();
        if (data)
            for (let i = 0; i < data.length; i++) {
                this.dataMap.set(data[i].key as string, data[i].val);
            }
        if (this.newVer()) {
            this.newVersion();
        }
    }
    public static clear() {
        this.dataMap.clear();
        localStorage.clear();
    }
    public static newVer() {
        let oldVer = localStorage.getItem("version");
        let res = !!oldVer && oldVer != version;
        return res;
    }
    public static Set(key: string, val: any) {
        this.dataMap.set(key, val);
    }
    public static Remove(key: string) {
        this.dataMap.delete(key);
    }
    public static Get<T>(key: string, defaultVal: T = null) {
        if (this.dataMap.has(key))
            return this.dataMap.get(key) as T;
        else
            return defaultVal;
    }
    /**新版本时进行的操作 */
    public static newVersion() {

    }
}
window['Stor'] = Stor